/**
 * 
 */
package org.mspring.mlog.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.mspring.mlog.service.HQLExecuteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Gao Youbo
 * @since 2012-12-31
 * @Description
 * @TODO
 */
@Service
@Transactional
public class HQLExecuteServiceImpl implements HQLExecuteService {

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    @Autowired
    @Required
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Session getSession() throws HibernateException {
        Session sess = getSessionFactory().getCurrentSession();
        if (sess == null) {
            sess = getSessionFactory().openSession();
        }
        return sess;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mspring.mlog.service.HQLExecuteService#query(java.lang.String)
     */
    @Override
    public List query(String hql) {
        // TODO Auto-generated method stub
        return getSession().createQuery(hql).list();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mspring.mlog.service.HQLExecuteService#query(java.lang.String,
     * Integer, Integer)
     */
    @Override
    public List query(String hql, Integer firstResult, Integer maxResults) {
        // TODO Auto-generated method stub
        Query query = getSession().createQuery(hql);
        if (firstResult != null) {
            query.setFirstResult(firstResult);
        }
        if (maxResults != null) {
            query.setMaxResults(maxResults);
        }
        return query.list();
    }

}
